package com.guoyh.procommon.base

import android.annotation.SuppressLint
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ViewUtils
import com.guoyh.baseutils.viewModel.SupportViewModel
import com.guoyh.mcommon.R
import com.guoyh.mcommon.databinding.MBaseeWebActivityBinding
import com.guoyh.pronet.BaseViewModel
import com.tencent.smtt.sdk.WebView
import me.bzcoder.easywebview.base.BaseX5WebView
import me.bzcoder.easywebview.common.CommonJavascriptInterface
import me.bzcoder.easywebview.common.X5WebChromeClient
import me.bzcoder.easywebview.common.X5WebViewClient
import me.bzcoder.easywebview.utils.FullscreenHolder
import me.bzcoder.easywebview.webinterface.IWebViewActivity

/**
 * 使用 tencent x5 内核处理网页
 * 1、放入对应jar
 * 2、application 初始化
 * 3、gradle ndk配置
 * 4、jniLibs 配置
 * 5、添加权限 READ_PHONE_STATE
 * 6、getWindow().setFormat(PixelFormat.TRANSLUCENT);
 */
abstract class BaseWebViewActivity :
    XBaseActivity<SupportViewModel, MBaseeWebActivityBinding>(), IWebViewActivity {

    override val layoutId: Int = R.layout.m_basee_web_activity

    override fun viewModelClass() = SupportViewModel::class.java


    override fun onCreate(savedInstanceState: Bundle?) {
        mDataBind =
            DataBindingUtil.bind(ViewUtils.layoutId2View(R.layout.m_basee_web_activity))!!
        mViewModel = ViewModelProvider(this).get(SupportViewModel::class.java)
        dataBindView = mDataBind.root
        super.onCreate(savedInstanceState)
    }


    /**
     * 获取加载链接
     */
    abstract fun getUrl(): String

    abstract fun getWebViewId(): Int

    abstract fun getLayout(): View

    // 进度条
    private var webView: BaseX5WebView? = null

    // 全屏时视频加载view
    private var videoFullView: FrameLayout? = null

    // 加载视频相关
    private var mWebChromeClient: X5WebChromeClient? = null


    override fun initView(savedInstanceState: Bundle?) {
        videoFullView = findViewById(R.id.baseWebFullView)
        mDataBind.baseWebGroup.removeAllViews()
        mDataBind.baseWebGroup.addView(getLayout())

        initWebView()

        showLoadingUi()
        webView!!.loadUrl(getUrl())
        getDataFromBrowser(intent)

    }


    override fun onPause() {
        super.onPause()
        webView?.onPause()
    }

    @SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
    protected fun initWebView() {
        webView = findViewById(getWebViewId())

        mWebChromeClient = X5WebChromeClient(this)
        webView!!.webChromeClient = mWebChromeClient
        // 与js交互
        webView!!.addJavascriptInterface(CommonJavascriptInterface(this), "injectedObject")
        webView!!.webViewClient = X5WebViewClient(this)
        webView!!.setOnLongClickListener { v: View? -> handleLongImage() }
    }


    override fun onResume() {
        super.onResume()
        webView?.onResume()
        // 支付宝网页版在打开文章详情之后,无法点击按钮下一步
        webView?.resumeTimers()
        // 设置为横屏
        if (requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
    }

    override fun onDestroy() {
        try {
            videoFullView?.removeAllViews()
            webView?.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            webView?.stopLoading()
            webView?.webChromeClient = null
            webView?.webViewClient = null
            webView?.destroy()
            webView = null
        } catch (e: Exception) {
            Log.e("X5WebViewActivity", e.message!!)
        }
        super.onDestroy()
    }

    //    @Override
    //    public boolean onOptionsItemSelected(MenuItem item) {
    //        switch (item.getItemId()) {
    //            case android.R.id.home:// 返回键
    //                handleFinish();
    //                break;
    //            case R.id.actionbar_share:// 分享到
    //                String shareText = webView.getTitle() + webView.getUrl();
    //                BaseTools.share(X5WebViewActivity.this, shareText);
    //                break;
    //            case R.id.actionbar_cope:// 复制链接
    //                if (!TextUtils.isEmpty(webView.getUrl())) {
    //                    BaseTools.copy(webView.getUrl());
    //                    Toast.makeText(this, "复制成功", Toast.LENGTH_LONG).show();
    //                }
    //                break;
    //            case R.id.actionbar_open:// 打开链接
    //                BaseTools.openLink(X5WebViewActivity.this, webView.getUrl());
    //                break;
    //            case R.id.actionbar_webview_refresh:// 刷新页面
    //                if (webView != null) {
    //                    webView.reload();
    //                }
    //                break;
    //            default:
    //                break;
    //        }
    //        return super.onOptionsItemSelected(item);
    //    }


    override fun showWebView() {
        webView!!.visibility = View.VISIBLE
    }

    override fun hideWebView() {
        webView!!.visibility = View.INVISIBLE
    }

    override fun fullViewAddView(view: View) {
        val decor = window.decorView as FrameLayout
        videoFullView = FullscreenHolder(this@BaseWebViewActivity)
        videoFullView!!.addView(view)
        decor.addView(videoFullView)
    }

    override fun showVideoFullView() {
        videoFullView!!.visibility = View.VISIBLE
    }

    override fun hideVideoFullView() {
        videoFullView!!.visibility = View.GONE
    }


    override fun hideProgressBar() {
    }

    override fun onPageFinished(view: WebView?, url: String?) {
        super.onPageFinished(view, url)
        showSuccessUi()

    }

    override fun startProgress(newProgress: Int) {
        if (newProgress == 100) {
            showSuccessUi()
        }
    }

    override fun getVideoFullView(): FrameLayout {
        return videoFullView!!
    }

    /**
     * 全屏时按返加键执行退出全屏方法
     */
    fun hideCustomView() {
        mWebChromeClient!!.onHideCustomView()
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }

    /**
     * 上传图片之后的回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        super.onActivityResult(requestCode, resultCode, intent)
        if (requestCode == X5WebChromeClient.FILE_CHOOSER_RESULT_CODE) {
            mWebChromeClient!!.mUploadMessage(intent, resultCode)
        } else if (requestCode == X5WebChromeClient.FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5) {
            mWebChromeClient!!.mUploadMessageForAndroid5(intent, resultCode)
        }
    }

    /**
     * 使用singleTask启动模式的Activity在系统中只会存在一个实例。
     * 如果这个实例已经存在，intent就会通过onNewIntent传递到这个Activity。
     * 否则新的Activity实例被创建。
     */
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        getDataFromBrowser(intent)
    }

    /**
     * 作为三方浏览器打开传过来的值
     * Scheme: https
     * host: www.jianshu.com
     * path: /p/1cbaf784c29c
     * url = scheme + "://" + host + path;
     */
    private fun getDataFromBrowser(intent: Intent) {
        val data = intent.data
        if (data != null) {
            try {
                val scheme = data.scheme
                val host = data.host
                val path = data.path
                val text = "Scheme: $scheme\nhost: $host\npath: $path"
                Log.e("data", text)
                val url = "$scheme://$host$path"
                webView!!.loadUrl(url)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 直接通过三方浏览器打开时，回退到首页
     */
    fun handleFinish() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            finishAfterTransition()
        } else {
            finish()
        }
    }

    /**
     * 长按图片事件处理
     */
    private fun handleLongImage(): Boolean {
        val hitTestResult = webView!!.hitTestResult
        // 如果是图片类型或者是带有图片链接的类型
        if (hitTestResult.type == WebView.HitTestResult.IMAGE_TYPE ||
            hitTestResult.type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE
        ) {
            // 弹出保存图片的对话框
            AlertDialog.Builder(this@BaseWebViewActivity)
                .setItems(arrayOf("查看大图", "保存图片到相册")) { dialog: DialogInterface?, which: Int ->
                    val picUrl = hitTestResult.extra
                    //获取图片
                    Log.e("picUrl", picUrl)
                    when (which) {
                        0 -> showPreviewPhoto(picUrl)
                        1 -> {
                        }
                        else -> {
                        }
                    }
                }
                .show()
            return true
        }
        return false
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back()
            return true
        }
        return false
    }

    protected fun back() {
        //全屏播放退出全屏
        if (mWebChromeClient!!.inCustomView()) {
            hideCustomView()

            //返回网页上一页
        } else if (webView!!.canGoBack()) {
            webView!!.goBack()

            //退出网页
        } else {
            handleFinish()
        }

    }

    override fun getActivity(): Activity {
        return this
    }

    private fun showPreviewPhoto(url: String) {
//        ImagePreview.getInstance()
//                .setContext(this)
//                .setImage(url)
//                .setFolderName("BigImageView/Download")
//                .setZoomTransitionDuration(300)
//                .setEnableClickClose(true)
//                .setEnableDragClose(true)
//                .setShowCloseButton(false)
//                .setShowDownButton(true)
//                .setShowIndicator(true)
//                // 设置失败时的占位图，默认为库中自带R.drawable.load_failed，设置为 0 时不显示
//                .setErrorPlaceHolder(R.drawable.load_failed)
//                // 设置查看原图时的百分比样式：库中带有一个样式：ImagePreview.PROGRESS_THEME_CIRCLE_TEXT，使用如下：
//                .setProgressLayoutId(ImagePreview.PROGRESS_THEME_CIRCLE_TEXT, new OnOriginProgressListener() {
//                    @Override
//                    public void progress(View parentView, int progress) {
//                        // 需要找到进度控件并设置百分比，回调中的parentView即传入的布局的根View，可通过parentView找到控件：
//                        ProgressBar progressBar = parentView.findViewById(R.id.sh_progress_view);
//                        TextView textView = parentView.findViewById(R.id.sh_progress_text);
//                        progressBar.setProgress(progress);
//                        String progressText = progress + "%";
//                        textView.setText(progressText);
//                    }
//
//                    @Override
//                    public void finish(View parentView) {
//
//                    }
//                })
//                .start();
    }



}

class WebViewModel : BaseViewModel() {

}